<?php 
	function missrain_setup(){
		//添加<title>标签
		add_theme_support( 'title-tag' );
		//添加文章和评论的rss
		add_theme_support( 'automatic-feed-links' );
		//添加文章和页面缩略图支持
		add_theme_support( 'post-thumbnails' );
		set_post_thumbnail_size( 195, 125, true ); 
		//添加主题菜单支持
		register_nav_menus(
		array(
			'left'    => __( '左边菜单', 'missrain' ),
			)
		);
		//搜索表单，评论表单，评论列表，输出有效的HTML5
		add_theme_support(
		'html5', array(
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
			)
		);
	}
	add_action('after_setup_theme','missrain_setup');
	
	//小工具
	function r_sidebar(){
        register_sidebar(array(
              'name' => __( '右边侧栏' ),
                'id' => 'right-sidebar',
                'before_widget' => '<div class="right-widget">',
                'after_widget' => '</div>',
                'before_title' => '<h3>',
                'after_title' => '</h3>',    
            ));
        }
    add_action('widgets_init','r_sidebar');

	//排列加载script和css
	function missrain_scripts() {
	    wp_enqueue_style( 'bootstrap-css', 'https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css', array(), '3.3.7' );
		//前台加载
		if( !is_admin() ){
			//加载bootstrap框架需要的文件
			wp_enqueue_script( 'bootstrap-js', 'https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js', array( 'jquery' ), '3.3.7', true );
			//bootstrap的IE支持
			wp_enqueue_script( 'HTML5-shim-js', 'https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js', array(), '3.7.3' );
			wp_enqueue_script( 'Respond-js', 'https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js', array(), '1.4.2' );
			wp_script_add_data( 'HTML5-shim-js', 'conditional', 'lt IE 9' );
			wp_script_add_data( 'Respond-js', 'conditional', 'lt IE 9' );
			//加载主题需要的script和css
			wp_enqueue_style( 'missrain-css', get_theme_file_uri( '/assets/css/missrain.css'), array('bootstrap-css'), '1.0.0');
			//wp_enqueue_script( 'missrain-js', get_theme_file_uri( '/assets/js/missrain.js'), array('bootstrap-js'), '1.0.0',true);
			//不在首页加载
			if( !(is_home() || is_front_page()) ){
			    wp_enqueue_style( 'fancybox-css', get_theme_file_uri( '/assets/css/fancybox.css'), array(), '1.0.0');
			    wp_enqueue_script( 'fancybox-js', get_theme_file_uri( '/assets/js/fancybox.js'), array('jquery'), '1.0.0',true);
			    wp_enqueue_script( 'post-js', get_theme_file_uri( '/assets/js/post.js'), array('jquery'), '1.0.0',true);
			}
			//在首页加载
			if(is_home() || is_front_page()){
			   //图片轮播
			   
			}
			
		}

	}
	add_action( 'wp_enqueue_scripts', 'missrain_scripts' );

	//后台禁用谷歌字体
	function remove_open_sans() {    
	    wp_deregister_style( 'open-sans' );    
	    wp_register_style( 'open-sans', false );    
	    wp_enqueue_style('open-sans','');    
	}    
	add_action( 'init', 'remove_open_sans' );

	//去除头部冗余代码
	remove_action('wp_head', 'feed_links_extra', 3);
	remove_action('wp_head', 'feed_links', 2, 1);
	remove_action('wp_head', 'rsd_link'); //移除离线编辑器开放接口
	remove_action('wp_head', 'wlwmanifest_link'); //移除离线编辑器开放接口
	remove_action('wp_head', 'index_rel_link'); //本页链接
	remove_action('wp_head', 'parent_post_rel_link'); //清除前后文信息
	remove_action('wp_head', 'start_post_rel_link'); //清除前后文信息
	remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
	remove_action('wp_head', 'rel_canonical'); //本页链接
	remove_action('wp_head', 'wp_generator'); //移除WordPress版本号
	remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0); //本页短链接
	add_filter('xmlrpc_enabled', '__return_false');
	add_filter('embed_oembed_discover', '__return_false');
	remove_action('wp_head', 'wp_oembed_add_discovery_links');
	remove_action('wp_head', 'wp_oembed_add_host_js');
	remove_filter('pre_oembed_result', 'wp_filter_pre_oembed_result', 10);
	//去除window._wpemojiSettings
	remove_action( 'admin_print_scripts',    'print_emoji_detection_script');
	remove_action( 'admin_print_styles',    'print_emoji_styles');
	remove_action( 'wp_head',        'print_emoji_detection_script',    7);
	remove_action( 'wp_print_styles',    'print_emoji_styles');
	remove_filter( 'the_content_feed',    'wp_staticize_emoji');
	remove_filter( 'comment_text_rss',    'wp_staticize_emoji');
	remove_filter( 'wp_mail',        'wp_staticize_emoji_for_email');
	// 屏蔽 REST API
	add_filter('rest_enabled', '__return_false');
	add_filter('rest_jsonp_enabled', '__return_false');
	// 移除头部 wp-json 标签和 HTTP header 中的 link
	remove_action('wp_head', 'rest_output_link_wp_head', 10);
	remove_action('template_redirect', 'rest_output_link_header', 11);
	//清除wp_footer带入的embed.min.js
	function missrain_deregister_embed_script() {
	    wp_deregister_script('wp-embed');
	}
	add_action('wp_footer', 'missrain_deregister_embed_script');
	//禁止 s.w.org
	function missrain_remove_dns_prefetch($hints, $relation_type) {
	    if ('dns-prefetch' === $relation_type) {
	        return array_diff(wp_dependencies_unique_hosts() , $hints);
	    }
	    return $hints;
	}
	add_filter('wp_resource_hints', 'missrain_remove_dns_prefetch', 10, 2);
	if( !is_admin() ){
		//去除jquery-migrate
		function cedaro_dequeue_jquery_migrate( $scripts ) {
	    if ( ! is_admin() && ! empty( $scripts->registered['jquery'] ) ) {
	        	$jquery_dependencies = $scripts->registered['jquery']->deps;
	        	$scripts->registered['jquery']->deps = array_diff( $jquery_dependencies, array( 'jquery-migrate' ) );
		    }
		}
		add_action( 'wp_default_scripts', 'cedaro_dequeue_jquery_migrate' );
	}
	

	//编辑器强化
	function add_more_buttons($buttons){  
		$buttons[] = 'fontsizeselect';  
		$buttons[] = 'styleselect';  
		$buttons[] = 'fontselect';  
		$buttons[] = 'hr';  
		$buttons[] = 'sub';  
		$buttons[] = 'sup';  
		$buttons[] = 'cleanup';  
		$buttons[] = 'image';  
		$buttons[] = 'code';  
		$buttons[] = 'media';  
		$buttons[] = 'backcolor';  
		$buttons[] = 'visualaid';  
		return $buttons;  
	}  
	add_filter("mce_buttons_3", "add_more_buttons");

	//文章加密
	function missrain_password_hint( $c ){
	global $post, $user_ID, $user_identity;
	if ( empty($post->post_password) )
		return $c;
	if ( isset($_COOKIE['wp-postpass_'.COOKIEHASH]) && stripslashes($_COOKIE['wp-postpass_'.COOKIEHASH]) == $post->post_password )
		return $c;
	if($hint = get_post_meta($post->ID, 'password_hint', true)){
		$url = get_option('siteurl').'/wp-pass.php';
		if($hint)
		$hint = __('密码提示：','tinection').$hint;
		else
		$hint = __("请输入您的密码",'tinection');
			if($user_ID)
			$hint .= sprintf(__('欢迎进入，您的密码是：','tinection'), $user_identity, $post->post_password);
			$out = <<<END
					<form method="post" action="$url">
					<p>__('这篇文章是受保护的文章，请输入密码继续阅读：','tinection')</p>
					<div>
					<label>$hint<br/>
					<input type="password" name="post_password"/></label>
					<input type="submit" value="__('输入密码','tinection')" name="Submit"/>
					</div>
					</form>
END;
		return $out;
		}else{
			return $c;
		}
	}
	add_filter('the_content', 'missrain_password_hint');

	//WordPress文字标签关键词自动内链
	$match_num_from = 1;		
	$match_num_to = 4;		
	function tag_sort($a, $b){
		if ( $a->name == $b->name ) return 0;
		return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
	}
	function missrain_tag_link($content){
		global $match_num_from,$match_num_to;
			$posttags = get_the_tags();
			if ($posttags) {
				usort($posttags, "tag_sort");
				$ex_word = '';
				$case = '';
				foreach($posttags as $tag) {
					$link = get_tag_link($tag->term_id);
					$keyword = $tag->name;
					$cleankeyword = stripslashes($keyword);
					$url = "<a href=\"$link\" class=\"tooltip-trigger tin\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('查看更多关于 %s 的文章'))."\"";
					$url .= ' target="_blank"';
					$url .= ">".addcslashes($cleankeyword, '$')."</a>";
					$limit = rand($match_num_from,$match_num_to);
					$content = preg_replace( '|(<a[^>]+>)(.*)<pre.*?>('.$ex_word.')(.*)<\/pre>(</a[^>]*>)|U'.$case, '$1$2$4$5', $content);
					$content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2$4$5', $content);
					$cleankeyword = preg_quote($cleankeyword,'\'');
					$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
					$content = preg_replace($regEx,$url,$content,$limit);
					$content = str_replace( '', stripslashes($ex_word), $content);
				}
			}
		return $content;
	}
	add_filter('the_content','missrain_tag_link',12);

	//激活菜单添加.action类
	function missrain_nav_menu_css_class( $classes ) {
     if ( in_array('current-menu-item', $classes ) OR in_array( 'current-menu-ancestor', $classes ) )
          $classes[]     =     'active';
     return $classes;
	}
	add_filter( 'nav_menu_css_class', 'missrain_nav_menu_css_class' );

	//无缩略图时抓取第一张图片或输出随机图片
	function post_thumbnail_src() {
	    global $post;
	    if ($values = get_post_custom_values("git_thumb")) { //输出自定义域图片地址
	        $values = get_post_custom_values("git_thumb");
	        $post_thumbnail_src = $values[0];
	    } elseif (has_post_thumbnail()) { //如果有特色缩略图，则输出缩略图地址
	        $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID) , 'full');
	        $post_thumbnail_src = $thumbnail_src[0];
	    } else {
	        $post_thumbnail_src = '';
	        ob_start();
	        ob_end_clean();
	        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	        @$post_thumbnail_src = $matches[1][0]; //获取该图片 src
	        if (empty($post_thumbnail_src)) { //如果日志中没有图片，则显示随机图片
	            $random = mt_rand(1, 6);
	            echo get_template_directory_uri();
	            echo '/assets/images/' . $random . '.jpg';
	            //如果日志中没有图片，则显示默认图片
	            //echo '/assets/img/thumbnail.png';
	        }
	    };
	    echo $post_thumbnail_src;
	}

    //WordPress禁止内容转义
    remove_filter('the_content', 'wptexturize');

	//时间以xx之前显示
	function timeago( $ptime ) {
		date_default_timezone_set ('ETC/GMT');
	    $ptime = strtotime($ptime);
	    $etime = time() - $ptime;
	    if($etime < 1) return '刚刚';
	    $interval = array (
	        12 * 30 * 24 * 60 * 60  =>  '年前 ('.date('Y-m-d', $ptime).')',
	        30 * 24 * 60 * 60       =>  '个月前 ('.date('m-d', $ptime).')',
	        7 * 24 * 60 * 60        =>  '周前 ('.date('m-d', $ptime).')',
	        24 * 60 * 60            =>  '天前',
	        60 * 60                 =>  '小时前',
	        60                      =>  '分钟前',
	        1                       =>  '秒前'
	    );
	    foreach ($interval as $secs => $str) {
	        $d = $etime / $secs;
	        if ($d >= 1) {
	            $r = round($d);
	            return $r . $str;
	        }
	    };
	}

	//文章图片添加fancybox类，用于图片灯箱，添加img-responsive用于图片自适应
	function fancybox ($content){
		global $post;
		$pattern = "/<a(.*?)href=('|\")([^>]*).(bmp|gif|jpeg|jpg|png|swf)('|\")(.*?)>(.*?)<\/a>/i";
		$replacement = '<a$1href=$2$3.$4$5 rel="box" class="img-responsive fancybox"$6>$7</a>';
		$content = preg_replace($pattern, $replacement, $content);
		return $content;
	}
	add_filter('the_content', 'fancybox');

	//wordpress上传文件重命名
	function git_upload_filter($file) {
    	$time = date("YmdHis");
    	$file['name'] = $time . "" . mt_rand(1, 100) . "." . pathinfo($file['name'], PATHINFO_EXTENSION);
    	return $file;
	}
	add_filter('wp_handle_upload_prefilter', 'git_upload_filter');

	//禁用自动保存
	function fanly_no_autosave() { 
		wp_deregister_script('autosave'); 
	}
	add_action('wp_print_scripts', 'fanly_no_autosave');

	//禁用版本修订
	function fanly_wp_revisions_to_keep( $num, $post ) { 
		return 0;
	}
	add_filter( 'wp_revisions_to_keep', 'fanly_wp_revisions_to_keep', 10, 2 );

	//将文章和评论的外链转为内链
	function convert_to_internal_links($content){
    	preg_match_all('/\shref=(\'|\")(http[^\'\"#]*?)(\'|\")([\s]?)/',$content,$matches);
    	if($matches){
    		foreach($matches[2] as $val){
    			if(strpos($val,home_url())===false){
    				$rep = $matches[1][0].$val.$matches[3][0];
    				$new = '"'.home_url().'/redirect/'.base64_encode($val).'" target="_blank"';
    				$content = str_replace("$rep","$new",$content);
    			}
    		}
    	}
    	return $content;
        }
        add_filter('the_content','convert_to_internal_links',99);
        add_filter('comment_text','convert_to_internal_links',99);
        add_filter('get_comment_author_link','convert_to_internal_links',99);
        function tin_redirect() {
        	$baseurl = 'redirect';
        	$request = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        	$hop_base = trailingslashit(trailingslashit(home_url()).$baseurl);
        	if (substr($request,0,strlen($hop_base)) != $hop_base)	return false;
        	$hop_key = str_ireplace($hop_base, '', $request);
        	if(substr($hop_key, -1) == '/')$hop_key = substr($hop_key, 0, -1);
        	if (!empty($hop_key)) {
        		$url = base64_decode($hop_key);
        		wp_redirect( $url, 302 );
        		exit;
        	}
    }
    add_action('template_redirect','tin_redirect');
?>